<template>

    <!-- 同意  驳回 等 按钮弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="审批流程"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <div class="comment-form">
      <el-form :model="form" label-width="120px">
        <el-form-item label="评论内容" required>
          <el-input
            v-model="form.plneirong"
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="无需办理人" v-if="form.tgblr">
          <el-checkbox v-model="form.noHandler">
            提前完成无需其他人办理
          </el-checkbox>
        </el-form-item>
        
        <el-form-item label="不合格类型" v-if="form.buhege === 1">
          <el-input
            v-model="form.buheglx"
            placeholder="请选择不合格类型"
            readonly
          >
            <template #append>
              <el-button type="primary">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="不合格人员" v-if="form.buhege === 1">
          <el-input
            v-model="form.buhegry"
            placeholder="请选择不合格人员"
            readonly
          >
            <template #append>
              <el-button type="primary">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">返回</el-button>
        <el-button 
          v-if="commentObj.pinglunlx === 0 || commentObj.pinglunlx === 10"
          type="success" 
          @click="handleSubmit"
        >
          同意
        </el-button>
        <el-button 
          v-if="commentObj.pinglunlx === 1"
          type="success" 
          @click="handleSubmit"
        >
          完成
        </el-button>
        <el-button 
          v-if="commentObj.pinglunlx === -1"
          type="danger" 
          @click="handleSubmit"
        >
          拒绝
        </el-button>
        <el-button 
          v-if="commentObj.pinglunlx === 97"
          type="warning" 
          @click="handleSubmit"
        >
          撤回
        </el-button>
        <el-button 
          v-if="commentObj.pinglunlx === 98"
          type="warning" 
          @click="handleSubmit"
        >
          驳回到上节点
        </el-button>
        <el-button 
          v-if="commentObj.pinglunlx === 98"
          type="warning" 
          @click="handleRejectToStart"
        >
          驳回到发起
        </el-button>
        <el-button 
          v-if="commentObj.pinglunlx === 999"
          type="primary" 
          @click="handleSubmit"
        >
          评论
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Base64 from '@/utils/base64.js'
import http from '@/utils/request.js'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  commentData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = ref(false)
const form = reactive({
  plneirong: '',
  banliren: '',
  buheglx: '',
  buhegry: '',
  tgblr: false,
  buhege: 0,
  noHandler: false
})

const commentObj = reactive({
  gobacklx: 0,
  id: 0,
  pinglunlx: 0,
  liuchengbh: '',
  liuchengzxbh: '',
  jiedianbh: '',
  faid: 0
})

let pllx = 0

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal && props.commentData) {
    initializeData()
  }
})

// 监听 dialogVisible 变化
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    emit('update:visible', false)
  }
})

const initializeData = () => {
  // 初始化评论对象数据
  Object.assign(commentObj, props.commentData)
  
  // 根据评论类型设置默认内容
  if (commentObj.pinglunlx === 0) {
    form.plneirong = '同意'
  } else if (commentObj.pinglunlx === 1) {
    form.plneirong = '完成'
  } else if (commentObj.pinglunlx === 97) {
    form.plneirong = '撤回'
  } else if (commentObj.pinglunlx === 98) {
    form.plneirong = '驳回'
  } else if (commentObj.pinglunlx === -1) {
    form.plneirong = '拒绝'
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const validateForm = () => {
  if (!form.plneirong.trim()) {
    ElMessage.error('评论内容不能为空！')
    return false
  }
  
  if (form.buheglx === '' && form.buhegry !== '') {
    ElMessage.error('不合格类型不能为空')
    return false
  }
  
  if (form.buheglx !== '' && form.buhegry === '') {
    ElMessage.error('不合格人员不能为空')
    return false
  }
  
  if (form.xsblr && form.banliren === '') {
    ElMessage.error('指定办理人不能为空！')
    return false
  }
  
  return true
}

const handleSubmit = async () => {
  pllx = commentObj.pinglunlx
  
  if (!validateForm()) {
    return
  }
  
  try {
    await ElMessageBox.confirm('确认要保存数据吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await saveComment()
  } catch (error) {
    // 用户取消操作
  }
}

const handleRejectToStart = async () => {
  pllx = -1
  
  if (!validateForm()) {
    return
  }
  
  try {
    await ElMessageBox.confirm('确认要保存数据吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await saveComment()
  } catch (error) {
    // 用户取消操作
  }
}

const saveComment = async () => {
  try {
    const bs64_cs = {
      pinglun: form.plneirong,
      banliren: form.banliren,
      pinglunlx: pllx,
      id: commentObj.id,
      openid: localStorage.getItem('openid') || "17524180246839845722", // 使用正确的openid
      liuchengbh: commentObj.liuchengbh,
      liuchengzxbh: commentObj.liuchengzxbh,
      jiedianbh: commentObj.jiedianbh
    }
    
    const cs = {
      ctype: 'app_pinglun_save',
      bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
      bs64_obj: '',
      bs64_list: '',
      ids: '',
      faid: 0
    }
    
    console.log('评论提交参数:', cs)
    console.log('评论bs64_cs解码:', bs64_cs)
    
    // 使用正确的API地址
    const response = await http.request({
      method: 'POST',
      url: 'https://vue.haozskj.com/xcx/ajax/Ajax_apppost.ashx',
      data: {
        canshu: cs
      }
    })
    
    console.log('评论提交结果:', response)
    
    if (response && response.leixing === 'ok') {
      ElMessage.success('操作成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(response?.msg || '操作失败')
    }
  } catch (error) {
    console.error('评论提交失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}
</script>

<style scoped>
.comment-form {
  padding: 20px 0;
}

.dialog-footer {
  text-align: center;
}

.dialog-footer .el-button {
  margin: 0 5px;
}
</style>
